package org.abc.fund.controller.trade;

import org.abc.fund.entity.trade.Account;
import org.abc.fund.service.trade.AccountService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/accounts")
public class AccountController {

  private final AccountService accountService;

  public AccountController(AccountService accountService) {
    this.accountService = accountService;
  }

  /**
   * API - 创建一个新账户. POST /api/accounts
   *
   * @param account 请求体中包含账户信息.
   * @return 成功时返回创建的账户和201状态码, 如果账户已存在则返回409.
   */
  @PostMapping
  public ResponseEntity<Account> createAccount(@RequestBody Account account) {
    try {
      Account createdAccount = accountService.createAccount(account);
      return new ResponseEntity<>(createdAccount, HttpStatus.CREATED);
    } catch (IllegalStateException e) {
      // 如果账户已存在，返回冲突状态码
      return ResponseEntity.status(HttpStatus.CONFLICT).build();
    }
  }

  /**
   * API - 根据用户ID查询账户. GET /api/accounts/{userId}
   *
   * @param userId 用户的ID.
   * @return 成功时返回账户信息和200状态码, 未找到则返回404.
   */
  @GetMapping("/{userId}")
  public ResponseEntity<Account> getAccountByUserId(@PathVariable Long userId) {
    return accountService
        .getAccountByUserId(userId)
        .map(ResponseEntity::ok)
        .orElse(ResponseEntity.notFound().build());
  }
}
